/*
 * @Author: 许旺玉
 * @Date: 2020-07-07 14:33:38
 * @LastEditTime: 2020-07-10 14:29:55
 * @LastEditors: Please set LastEditors
 * @Description: 封装接口地址
 * @FilePath: \jingkaisystem\src\api\apiConfig.js
 */

import axios from "axios"
import { Loading, Message } from 'element-ui';
// import storage from "../utils/storage.js"  //引入storeage方法
import store from "../store/index.js"  //用vuex拿去token
import router from "../router/index.js"


let loadingInstance;

const httpRequest = axios.create({
    baseURL: '/api',//基本地址
    timeout: 5000,//超时时间
    headers: {
        "content-type": "application/x-www-form-urlencoded"
    }
})

// 请求拦截
httpRequest.interceptors.request.use(function (config) {
    // window.console.log("请求拦截"+config)
    loadingInstance = Loading.service();
    return config;
}, function (error) {
    return Promise.reject(error);
});



httpRequest.interceptors.response.use(function (response) {
    loadingInstance.close();
    return response;
}, function (error) {
    return Promise.reject(error);
});

//请求头携带token
httpRequest.interceptors.request.use((config) => {
    // console.log(config)
    if (store.state.loginModule.examToken) { //判断loginModule是否有token
        config.headers.token = store.state.loginModule.examToken //携带token
    }
    return config
}, (error) => {
    return Promise.reject(error)
});


// 响应拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log(response.data.statusCode)
    if (response.data.statusCode == "300") {
        Message.error("账号或密码错误！！！！！！")
        router.replace("/login")
    } else if (response.data.statusCode == "1006") {
        Message.error("没有token重新登录！！！！！！")
        router.replace("/login")
    }
    return response;

}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});



export default httpRequest